package cn.jinjimi.app.main.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.view.View;
import android.widget.RelativeLayout;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.URLUtil;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.ChannelId;
import cn.jinjimi.app.bean.Source;
import cn.jinjimi.domain.data.dto.AdvDto;
import cn.jinjimi.app.entity.Advertisement;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.store.dao.CacheDao;
import cn.jinjimi.app.main.activity.MainActivity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.RoundProgressBar;

import java.util.List;

/**
 * Created by Administrator on 2015/5/5.
 */
public class StartPicFragment extends BaseFragment implements View.OnClickListener {

    private SimpleDraweeView mPicIv;
    private RelativeLayout rlSkip;
    private RoundProgressBar roundProgressBar;

    private Advertisement advertisement = null;
    private ObjectAnimator animation;
    private boolean skipWait;
    private List<Advertisement> advertisementList = null;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_start_pic;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mPicIv = (SimpleDraweeView) findView().findViewById(R.id.encourage_pic);
        rlSkip = (RelativeLayout) findView().findViewById(R.id.rl_skip);
        roundProgressBar = (RoundProgressBar) findView().findViewById(R.id.round_progressbar);
    }

    protected void initListener() {
        mPicIv.setOnClickListener(this);
        rlSkip.setOnClickListener(this);

    }

    protected void initData() {
        advertisementList = AdvDto.getAdvtisementsByCache(CacheDao.SPLASHSCREENADVCACHE);
        if (advertisementList != null && advertisementList.size() > 0) {
            long startedTime;
            long endedTime;
            long currentTime = System.currentTimeMillis();
            for (Advertisement advertisement1 : advertisementList) {
                if (!isNotEmptyUrl(advertisement1) || advertisement1.advertisementsPlanId == 0)
                    continue;
                startedTime = advertisement1.startedTime;
                endedTime = advertisement1.endedTime;
                if ((endedTime > 0 && currentTime > startedTime && currentTime < endedTime)
                        || (endedTime == 0 && currentTime > startedTime)) {
                    if (advertisement == null) {
                        advertisement = advertisement1;
                    } else if (advertisement.startedTime < advertisement1.startedTime) {
                        advertisement = advertisement1;
                    }
                }
            }
            if (isNotEmptyUrl(advertisement)) {
                loadPic(advertisement);
            } else {
                toMain();
            }
        } else {
            toMain();
        }
    }

    public static String getDisPlayStr() {
        int[] screenSize = AndroidUtils.getScreeSize();
        return screenSize[0] + "x" + screenSize[1];
    }

    private boolean isNotEmptyUrl(Advertisement advertisement) {
        if (advertisement != null && advertisement.resources != null
                && !advertisement.resources.isEmpty() && advertisement.resources.get(0) != null
                && advertisement.resources.get(0).attchments != null
                && !advertisement.resources.get(0).attchments.isEmpty()
                && advertisement.resources.get(0).attchments.get(0) != null
                && StringUtils.isNotEmpty(advertisement.resources.get(0).attchments.get(0).imgUrl)) {
            return true;
        } else {
            return false;
        }
    }

    private void loadPic(final Advertisement advertisement) {
        String url = advertisement.resources.get(0).attchments.get(0).imgUrl
                + "?imageMogr2/thumbnail/" + getDisPlayStr();

        ControllerListener controllerListener = new BaseControllerListener() {
            @Override
            public void onFinalImageSet(String id, Object imageInfo, Animatable animatable) {
                super.onFinalImageSet(id, imageInfo, animatable);
                int position = advertisementList.indexOf(advertisement);
                advertisementList.set(position, advertisement);
                AdvDto advDto = new AdvDto();
                advDto.data = advertisementList;
                DatabaseManager.getInstance().getCacheDao().saveCacheData(advDto, CacheDao.SPLASHSCREENADVCACHE);
                beginProgressAnimation();
            }

            @Override
            public void onFailure(String id, Throwable throwable) {
                super.onFailure(id, throwable);
                if (rlSkip != null)
                    rlSkip.setVisibility(View.GONE);
                toMain();
            }
        };

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setControllerListener(controllerListener)
                .setUri(Uri.parse(url))
                .build();
        mPicIv.setController(controller);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.encourage_pic://点击励志图
                if (advertisement == null || advertisement.resources == null
                        || advertisement.resources.isEmpty() || advertisement.resources.get(0) == null)
                    return;
                if (StringUtils.isNotEmpty(advertisement.resources.get(0).linkUrl)) {
                    toAdDetail(URLUtil.appendParam(advertisement.resources.get(0).linkUrl, EventDataField.ParamOutChannel, ChannelId.Splash, true));
                }
                break;
            case R.id.rl_skip:
                skipAdsToMain();
                break;
        }
    }

    @EventTrace(EventID.APP_ELUNCH_WAIT)
    private void waitToMain() {
        toMain();
    }

    @EventTrace(EventID.APP_ELUNCH_FORWARD)
    private void skipAdsToMain() {
        skipWait = true;
        toMain();
    }

    /* 打开广告详情（之前先启动首页） */

    @EventTrace(EventID.APP_ELUNCH_DETAIL)
    private void toAdDetail(@EventTraceParam(EventDataField.ParamTo) String redirectUrl) {
        skipWait = true;
        toMain();
        Router router = Router.create(getActivity(), redirectUrl);
        if (AccountManager.getInstance().isLogin()) {
            router.addParam("token", AccountManager.getInstance().getAccount().token);
        }
        router.addParam(BundleKey.SOURCE, Source.LUNCH).open();
    }

    /* 打开首页 */
    private void toMain() {
        if (getActivity() == null) {
            return;
        }
        Intent intent = new Intent(getActivity(), MainActivity.class);
        startActivity(intent);
        getActivity().finish();
    }

    /* 圆环动画开启 */
    private void beginProgressAnimation() {
        rlSkip.setVisibility(View.VISIBLE);

        animation = ObjectAnimator.ofInt(roundProgressBar, "progress", 100, 0).setDuration(3000);
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (checkActivityExit() || skipWait)
                    return;
                waitToMain();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animation.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (animation != null) {
            animation.cancel();
            animation = null;
        }
    }
}
